package user

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"server/app/api/request/common"
	user2 "server/app/api/request/user"
	"server/base"
	user3 "server/common/models/user"
	"server/common/utils"
	"server/pkg/response"
)

var Moment = new(moment)

type moment struct{}

func (*moment) Post(c *gin.Context) {
	var req user2.MomentCreate
	err := c.ShouldBind(&req)
	if err != nil {
		response.Error(c, req.GetError(err))
		return
	}

	// create a message into mysql databases
	userMoment := req.ToModel(utils.GetUserId(c))
	base.App.Mysql.Object.Create(&userMoment)
	if userMoment.UserId == 0 {
		response.Error(c, "发布失败")
		return
	}

	response.Success(c, gin.H{})
}

func (*moment) Pull(c *gin.Context) {
	var req common.PageReq
	err := c.ShouldBind(&req)
	if err != nil {
		response.Error(c, "参数有误")
		return
	}

	type dataResponse struct {
		user3.UserMoment
		UserNickname string `json:"user_nickname"`
		UserAvatar   string `json:"user_avatar"`
	}

	where := ""
	if req.LateId != 0 {
		where = fmt.Sprintf(" where user_moments.id < %d", req.LateId)
	}

	var userMoment []dataResponse
	base.Mysql.Raw(`
		select user_moments.*,users.nickname as user_nickname,users.avatar as user_avatar from user_moments 
		    left join users on user_moments.user_id = users.id `+where+`  order by id desc limit ? offset ?
	`, req.GetLimit(), req.GetOffset()).Scan(&userMoment)
	response.Success(c, gin.H{"list": userMoment})
}
